<?php

require_once ('initialize.php');

//POST Request
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    include_once(Utils::getPath(array('repositories', 'userRepository.php')));

    if (isset($_POST['usernameLog']) && isset($_POST['passwordLog'])) {
        $userRep = new UserRepository();
        $user = $userRep->findByUserName($_POST['usernameLog']);

        if (!is_null($user) && $user->validatePassword($_POST['passwordLog'])) {
            $_SESSION['authenticated'] = true;
            $_SESSION['authenticatedId'] = $user->getId();
            $_SESSION['authenticatedUserName'] = $user->getUserName();
        } else {
            $errorMes = 'Username or password not valid';
            if ($request_ajax) {
                    echo json_encode(array('authenticated' => false, 'error' => $errorMes));
                    exit();
            } else {
                Utils::showError($errorMes);

                $referer = getenv("HTTP_REFERER");
                header("Location: $referer");

                exit();
            }
        }
    }
    $location = Utils::getUrl('profile.php');
    if ($request_ajax) {
        echo json_encode(array('authenticated' => true, 'location' => $location));
        exit();
    } else {
        header('Location: ' . $location);
        exit();
    }
}